package cn.regexp.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具
 */
@Slf4j
public class UploadUtil {

    /**
     * 上传文件到阿里云 oss
     *
     * @param file 待上传文件
     * @return 文件名
     * @throws Exception 异常
     */
    public static String uploadAli(MultipartFile file) throws Exception {
        // 获取阿里云 OSS 配置信息
        String endpoint = ResourceUtil.getConfigByName("oss.endpoint");
        String accessKeyId = ResourceUtil.getConfigByName("oss.accessKeyId");
        String accessKeySecret = ResourceUtil.getConfigByName("oss.accessKeySecret");
        String bucketName = ResourceUtil.getConfigByName("oss.bucketName");
        String imageDir = ResourceUtil.getConfigByName("oss.imageDir");
        // 生成文件名称
        String nanoId = NanoIdUtils.randomNanoId();
        // 获取真实文件名称 logo.png
        String orgFileName = file.getOriginalFilename();
        // 获取拓展名字 .png
        String ext = "." + FilenameUtils.getExtension(orgFileName);
        // 获取文件名 UT1g96IBT3cHEledMD4zn.jpg
        String fileName = nanoId + ext;
        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 上传文件流
            ossClient.putObject(bucketName, imageDir + fileName, file.getInputStream());
            return fileName;
        } catch (OSSException oe) {
            log.error("文件上传成功，接收响应失败！");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("文件上传失败！");
            log.error("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
























